package com.ysjl.badminton.mq;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ysjl.badminton.utils.HttpUtils;
import com.ysjl.badminton.vo.WXMsgVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

/**
 * 泛型可选
 */
@Slf4j
@Component
@RocketMQMessageListener(consumerGroup = "badminton", topic = "badminton")
public class RocketMQConsumer implements RocketMQListener<String> {

    private static String WX_API_HOSTNAME = "https://qyapi.weixin.qq.com";
    private static String WX_API_GETTOKEN = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ww32355b024bba3ae7&corpsecret=P0_uaPMyinUu3Ed-z85tzzDBYv8xLDJh1rmQvSojLAc";
    private static String WX_API_SENDMSG = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=";

    @Override
    public void onMessage(String message) {
        log.info(message);
        this.sendMsg(message);
    }

    /**
     * 发送消息
     * @param content
     * @return
     */
    private String sendMsg(String content) {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = null;
        String token = null;
        String res = null;
        int code = 0;

        try {
            // 先判断是否存在token
            token = this.getToken();

            // 再组装消息发送
            WXMsgVo vo = new WXMsgVo();
            WXMsgVo.TextMsg msg = new WXMsgVo.TextMsg();
            vo.setAgentid("1000003");
            vo.setMsgtype("text");
            vo.setTouser("@all");
            msg.setContent(content);
            vo.setText(msg);

            res = HttpUtils.httpsPostWithJson(WX_API_HOSTNAME, WX_API_SENDMSG + token, mapper.writeValueAsString(vo));
            if (StringUtils.isNotEmpty(res)) {
                rootNode = mapper.readTree(res);
                code = rootNode.path("errcode").intValue();
                if (0 != code) {
                    log.error("发送消息失败:" + rootNode.path("errmsg").textValue());
                }
            }
        }
        catch (Exception e) {
            log.error("发送消息失败！", e);
        }
        return null;
    }

    private String getToken() {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = null;
        String token = null;
        String res = HttpUtils.getHttps(WX_API_HOSTNAME, WX_API_GETTOKEN);
        if (StringUtils.isNotEmpty(res)) {
            try {
                rootNode = mapper.readTree(res);
            } catch (JsonProcessingException e) {
                log.error("Token获取失败！", e);
            }
            token = rootNode.path("access_token").textValue();
        }
        return token;
    }

}
